import numpy as np
from tensorflow.keras.datasets import mnist
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier
import time

# 下载并加载 MNIST 数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
print("MNIST loaded successfully!")

# 数据预处理
train_images = train_images / 255.0
test_images = test_images / 255.0

# 将图像数据展平为一维向量
train_images = train_images.reshape((train_images.shape[0], -1))
test_images = test_images.reshape((test_images.shape[0], -1))

# 使用SVM进行分类
print("SVM:")
start_time = time.time()
clf = svm.SVC(gamma=0.01)
clf.fit(train_images, train_labels)
y_pred = clf.predict(test_images)
end_time = time.time()

# 计算准确率和计算时间
accuracy = accuracy_score(test_labels, y_pred)
print(f'SVM Accuracy: {accuracy}')
print(f'SVM Time: {end_time - start_time} seconds')

# 使用MLP进行分类
print("MLP:")
start_time = time.time()
mlp = MLPClassifier(hidden_layer_sizes=(50,), max_iter=1000)
mlp.fit(train_images, train_labels)
y_pred_mlp = mlp.predict(test_images)
end_time = time.time()

# 计算准确率和计算时间
accuracy_mlp = accuracy_score(test_labels, y_pred_mlp)
print(f'MLP Accuracy: {accuracy_mlp}')
print(f'MLP Time: {end_time - start_time} seconds')